
<template>
  <div class="container card-carousel-wrapper">
    <div class="card-carousel--nav__left" :disabled="atHeadOfList" @click="moveCarousel(-1)" />
    <div class="card-carousel">
      <div class="card-carousel--overflow-container">
        <div class="card-carousel-cards" :style="{ transform: 'translateX' + '(' + currentOffset + 'px' + ')'}">
          <div v-for="item in myschedule" :key="item.book.id" class="card-carousel--card" style="width: 300px; height: 300px;" @click="handleSecondKill(item)">

            <div style="width:300px;height:160px;margin:auto" class="xiangou-div">
              <img :src="item.book? item.book.bookImgs[0].imgName : ''" style="width:180px;height:180px;margin-left: 66px">
            </div>
            <div>
              <h3 style="margin-left:20px">{{ item.book.bookName }}</h3>
              <div style="margin-left:20px">
                <del style="font-size: 3px; "> 原价:  {{ item.book.price }} </del>
                <span style="color: red;margin-left:20px"> 折扣价:  {{ item.killPrice }} </span>
              </div>
              <div style="margin-left:20px;font-size:10px">
                <p v-if="item.book.repositoryNum < 500"> 库存仅剩：{{ item.book.repositoryNum }}</p>
                <p v-else-if="item.book.repositoryNum >= 500 & item.book.repositoryNum < 1000"> 库存: <span style="margin-left:10px">500+</span></p>
                <p v-else> 库存充足</p>
              </div>
              <p v-if="judge(item)" style="margin-left:20px;font-size:10px"> 限购截至日期 {{ item.endTime }}</p>
              <p v-else style="margin-left:20px;font-size:10px"> 秒杀倒计时 {{ item.formatTime }}</p>
              <i
                class="el-icon-bank-card"
                style="color: rgba(85, 165, 71, 0.65);float: right;font-size: 40px;position: relative;top: -50px;left: -30px;"
              />
            </div>

          </div>
        </div>
      </div>
    </div>
    <div class="card-carousel--nav__right" :disabled="atEndOfList" @click="moveCarousel(1)" />

    <el-dialog title="订单填写" :visible.sync="outerVisible">
      <el-form :model="form">
        <el-form-item label="物品名称" label-width="100px">
          <el-input v-model="orderObjectName" style="width:600px" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="购买数量" label-width="100px">
          <el-input-number v-model="form.num" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="购买价格" label-width="100px">
          <el-input-number v-model="form.price" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="总价格" label-width="100px">
          <el-input-number v-model="form.totalPrice" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="订单地址" label-width="100px">
          <el-select v-model="form.orderAdd" style="width:600px" placeholder="请选择收货地址">
            <template slot="empty">
              <div id="empty"><a href="#/profile">  请先去个人中心填写地址信息</a></div>
            </template>
            <el-option v-for="(item, index) in options" :key="index" :label="item.addr" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleBuySecondKill">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { postSecondKillBook } from '@/api/secondKill'
export default {
  props: {
    schedules: Array
  },
  data() {
    return {
      currentOffset: 0,
      windowSize: 5,
      paginationFactor: 320,
      form: {
        price: 0
      },
      orderObjectName: '',
      outerVisible: false,
      options: [],
      miaoshalist: [],
      myschedule: [],
      zhouMap: {
        'MON': 1,
        'TUE': 2,
        'WED': 3,
        'THU': 4,
        'FRI': 5,
        'SAT': 6,
        'SUN': 7
      },
      status: 0
    }
  },
  computed: {
    atEndOfList() {
      return this.currentOffset <= (this.paginationFactor * -1) * (this.schedules.length - this.windowSize)
    },
    atHeadOfList() {
      return this.currentOffset === 0
    },
    isLogin() {
      return this.$store.getters.isLogin
    },
    userDetail() {
      return this.$store.getters.userDetail
    }
  },
  // filters: {
  //   covertTrickTimeToDaoJiShi(value){
  //      return  value.nextTrickTime
  //   }
  // },
  watch: {
    form: function(newV, oldV) {
      newV.totalPrice = newV.price * newV.num
    },
    schedules: function(newValue, oldValue) {
      for (const key in this.schedules) {
        const element = this.schedules[key]
        if (element.corn.indexOf('/') === -1) {
          this.miaoshalist.push(key)
        }
      }

      const tmpList = this.deepClone2(this.schedules)
      // console.log(tmpList)
      if (this.status === 0) {
        setInterval(() => {
          // 把倒计时放在h1标签中
          for (const item of this.miaoshalist) {
            var ele = parseInt(item)
            var result = this.formatTrickTime(tmpList[ele].corn)
            this.$set(tmpList[ele], 'formatTime', this.daojiShi(result))
          }
          this.myschedule = tmpList
        }, 1000)
        this.status = 1
      }
      // console.log(this.miaoshalist)
    }
  },
  created() {

  },
  methods: {
    formatTrickTime(corn) {
      var strs = corn.split(' ')
      var second = strs[0]
      var minus = strs[1]
      var hour = strs[2]
      var zhou = this.zhouMap[strs[5]]
      // console.log(strs)
      var curDate = new Date()
      if (strs[3] === '?') {
        var date = new Date()
        date.setHours(parseInt(hour))
        date.setMinutes(parseInt(minus))
        date.setSeconds(parseInt(second))
        if (zhou === curDate.getDay() && date.getTime() > curDate.getTime()) {
          curDate.setDate(curDate.getDate())
          curDate.setHours(parseInt(hour))
          curDate.setMinutes(parseInt(minus))
          curDate.setSeconds(parseInt(second))
          return curDate.getTime()
        } else if (zhou === curDate.getDay() && curDate.getTime() - date.getTime() <= 60 * 1000) {
          return -1
        } else {
          var t = zhou - curDate.getDay() <= 0 ? zhou + 7 - curDate.getDay() : zhou - curDate.getDay()
          console.log(zhou)
          console.log(zhou - curDate.getDay() < 0)
          console.log(t)
          curDate.setDate(curDate.getDate() + t)
          curDate.setHours(parseInt(hour))
          curDate.setMinutes(parseInt(minus))
          curDate.setSeconds(parseInt(second))
          return curDate.getTime()
        }
      } else if (strs[5] === '?') {
        // console.log('{}hour{} , {}minus{} , {}second{} ', hour, curDate.getHours(), minus, curDate.getMinutes(), second, curDate.getSeconds())

        var date2 = new Date()
        date2.setHours(parseInt(hour))
        date2.setMinutes(parseInt(minus))
        date2.setSeconds(parseInt(second))
        // console.log(date2.getTime())
        // console.log(curDate.getTime())
        if (date2.getTime() > curDate.getTime()) {
          return date2.getTime()
        } else {
          curDate.setDate(curDate.getDate() + 1)
          curDate.setHours(parseInt(hour))
          curDate.setMinutes(parseInt(minus))
          curDate.setSeconds(parseInt(second))
          return curDate.getTime()
        }
        // if (hour >= curDate.getHours() && minus >= curDate.getMinutes() && second >= curDate.getSeconds()) {
        //   curDate.setDate(curDate.getDate())
        //   curDate.setHours(parseInt(hour))
        //   curDate.setMinutes(parseInt(minus))
        //   curDate.setSeconds(parseInt(second))
        //   return curDate.getTime()
        // }
        // curDate.setDate(curDate.getDate() + 1)
        // curDate.setHours(parseInt(hour))
        // curDate.setMinutes(parseInt(minus))
        // curDate.setSeconds(parseInt(second))
        // return curDate.getTime()
      }
    },
    deepClone2(obj) {
      var _obj = JSON.stringify(obj)
      var objClone = JSON.parse(_obj)
      return objClone
    },
    daojiShi(storptimes) {
      var newtime = new Date() // 获取当前时间
      // var storptime = new Date(storptimes) // 获取截止时间
      // console.log(storptimes)
      var mistiming = storptimes - newtime.getTime() //   获取截止时间距离现在的毫秒差

      var days = Math.floor(mistiming / 1000 / 60 / 60 / 24) // 获取天数
      var hours = Math.floor(mistiming / 1000 / 60 / 60 % 24) // 获取小时
      var minutes = Math.floor(mistiming / 1000 / 60 % 60) // 获取分钟数
      var seconds = Math.floor(mistiming / 1000 % 60) // 获取秒数

      // 判断天、时、分、秒是不是两位数，如果是直接输出，如果不是在前边加个0;
      days < 10 ? days = '0' + days : days
      hours < 10 ? hours = '0' + hours : hours
      minutes < 10 ? minutes = '0' + minutes : minutes
      seconds < 10 ? seconds = '0' + seconds : seconds

      // 第一种连接方法
      // var rels = days + "天" + hours + "时" + minutes + "分" + seconds + "秒";
      // 第二种连接方法
      var rels = `${days}天${hours}时${minutes}分${seconds}秒`

      // 判断时间差是不是正数，就是截止时间是不是比现在的时间晚
      var mis = mistiming > 0 ? rels : '秒杀开始'
      return mis
    },

    judge(item) {
      return item.corn.indexOf('/') !== -1
    },
    handleBuySecondKill() {
      const vm = this
      // console.log(vm.form)
      postSecondKillBook(vm.form).then(res => {
        // console.log(res)
        if (res.code === 200) {
          vm.form = {}
          vm.$message.success('购买成功')
        }
      })
      this.outerVisible = false
    },
    handleSecondKill(e) {
      if (!this.isLogin) {
        this.$message.warning('请先登录')
        return
      }
      const t = {}
      this.orderObjectName = e.book.bookName
      t.num = 1
      t.price = e.killPrice
      t.fkUserId = this.userDetail.id
      t.fkBookId = e.fkBookId
      t.status = 0
      this.form = t
      const vm = this
      // console.log(this.userDetail)
      this.$store.dispatch('address/getUserAddress', this.userDetail.id)
        .then(function(res) {
          // console.log(res.object)
          const items = res.object
          const temp = []
          for (const key in items) {
            const item = items[key]
            var ele = {}
            ele.id = item.id
            ele.addr = item.province + item.city + item.town + ' ' + item.detail +
         ' (' + item.username + '' + '收)' + ' ' + item.phone
            temp.push(ele)
          }
          vm.options = temp
        })

      this.outerVisible = true
    },
    moveCarousel(direction) {
      // Find a more elegant way to express the :style. consider using props to make it truly generic
      // console.log(this.schedules.length)
      // alert((this.paginationFactor * -1) * (this.schedules.length - this.windowSize))
      if (direction === 1 && !this.atEndOfList) {
        this.currentOffset -= this.paginationFactor
      } else if (direction === -1 && !this.atHeadOfList) {
        this.currentOffset += this.paginationFactor
      }
      // alert(this.currentOffset)
    }
  }
}
</script>
<style lang="scss" scoped >
.container{
   height:100%;
   margin-top: 50px;
   background-color: white;
}
.mycard{
  height: 100px;
  width: 200px
}
.test{
  border:1px solid black
}
#empty{
      font: 400 13.3333px Arial;
    height: 50px;
    text-align: center;
    /* margin: auto; */
    line-height: 50px
}
body {
  background: #f8f8f8;
  color: #2c3e50;
  font-family: 'Source Sans Pro', sans-serif;
  min-height: 1000px;
  padding:0;
  margin:0;
}
.card-carousel-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0 40px;
  color: #666a73;
}

.card-carousel {
  display: flex;
  justify-content: center;
  width: 1300px;
  width: 100%;
}
.card-carousel--overflow-container {
  overflow: hidden;
}
.card-carousel--nav__left, .card-carousel--nav__right {
  display: inline-block;
  width: 15px;
  height: 15px;
  padding: 10px;
  box-sizing: border-box;
  border-top: 2px solid #42b883;
  border-right: 2px solid #42b883;
  cursor: pointer;
  margin: 0 10px;
  transition: transform 150ms linear;
}
.card-carousel--nav__left[disabled], .card-carousel--nav__right[disabled] {
  opacity: 0.2;
  border-color: black;
}
.card-carousel--nav__left {
  transform: rotate(-135deg);
}
.card-carousel--nav__left:active {
  transform: rotate(-135deg) scale(0.9);
}
.card-carousel--nav__right {
  transform: rotate(45deg);
}
.card-carousel--nav__right:active {
  transform: rotate(45deg) scale(0.9);
}

.card-carousel-cards {
  display: flex;
  transition: transform 150ms ease-out;
  transform: translatex(0px);
}
.card-carousel-cards .card-carousel--card {
  margin: 0 10px;
  cursor: pointer;
  box-shadow: 0 4px 15px 0 rgba(40, 44, 53, 0.06), 0 2px 2px 0 rgba(40, 44, 53, 0.08);
  background-color: #fff;
  border-radius: 4px;
  z-index: 3;
  margin-bottom: 2px;
}
.card-carousel-cards .card-carousel--card:first-child {
  margin-left: 0;
}
.card-carousel-cards .card-carousel--card:last-child {
  margin-right: 0;
}
.card-carousel-cards .card-carousel--card img {
  vertical-align: bottom;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  transition: opacity 150ms linear;
  user-select: none;
}
.card-carousel-cards .card-carousel--card img:hover {
  opacity: 0.5;
}
.card-carousel-cards .card-carousel--card--footer {
  border-top: 0;
  padding: 7px 15px;
}
.card-carousel-cards .card-carousel--card--footer p {
  padding: 3px 0;
  margin: 0;
  margin-bottom: 2px;
  font-size: 19px;
  font-weight: 500;
  color: #2c3e50;
  user-select: none;
}
.card-carousel-cards .card-carousel--card--footer p:nth-of-type(2) {
  font-size: 12px;
  font-weight: 300;
  padding: 6px;
  background: rgba(40, 44, 53, 0.06);
  display: inline-block;
  position: relative;
  margin-left: 4px;
  color: #666a73;
}
.card-carousel-cards .card-carousel--card--footer p:nth-of-type(2):before {
  content: "";
  float: left;
  position: absolute;
  top: 0;
  left: -12px;
  width: 0;
  height: 0;
  border-color: transparent rgba(40, 44, 53, 0.06) transparent transparent;
  border-style: solid;
  border-width: 12px 12px 12px 0;
}
.card-carousel-cards .card-carousel--card--footer p:nth-of-type(2):after {
  content: "";
  position: absolute;
  top: 10px;
  left: -1px;
  float: left;
  width: 4px;
  height: 4px;
  border-radius: 2px;
  background: white;
  box-shadow: -0px -0px 0px #004977;
}

</style>
